package com.company.代理模式2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Utils {
    public static <T> T getAgentProxy(Class targetClass,Class<T> proxyInterfaceClass,BeforeAfterAction action) throws IllegalAccessException, InstantiationException {
        Object target = targetClass.newInstance();//代理目标对象

        Object proxyObj = Proxy.newProxyInstance(
                targetClass.getClassLoader(),
                new Class[]{proxyInterfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        action.before();
                        method.invoke(target,args);
                        action.after();
                        return null;
                    }
                }
        );
        return (T)proxyObj;
    }
}
